package com.micro.school.system.controller.student;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.core.utils.poi.ExcelUtil;
import com.micro.school.common.core.web.controller.BaseController;
import com.micro.school.common.core.web.domain.AjaxResult;
import com.micro.school.common.core.web.page.TableDataInfo;
import com.micro.school.common.security.utils.SecurityUtils;
import com.micro.school.system.api.RemoteEduService;
import com.micro.school.system.api.RemoteUserService;
import com.micro.school.system.api.domain.vo.*;
import com.micro.school.system.domain.StudentInfo;
import com.micro.school.system.domain.vo.BatchLogDetailVo;
import com.micro.school.system.service.IBatchLogDetailService;
import com.micro.school.system.utils.FileDownloadUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.micro.school.system.domain.vo.StudentBatchLogVo;
import com.ruoyi.system.service.IStudentBatchLogService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 * 
 * @author rakic
 * @date 2025-08-05
 */
@RestController
@RequestMapping("/log")
public class StudentBatchLogController extends BaseController
{
    @Autowired
    private IStudentBatchLogService studentBatchLogService;

    @Resource
    private IBatchLogDetailService batchLogDetailService;

    @Resource
    private RemoteEduService remoteEduService;

    @Resource
    private RemoteUserService remoteUserService;


    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/list")
    public TableDataInfo list(StudentBatchLogVo studentBatchLogVo)
    {
        startPage();
        studentBatchLogVo.setTenantId(Integer.parseInt(SecurityContextHolder.getUserTenantId()));
        List<StudentBatchLogVo> list = studentBatchLogService.selectStudentBatchLogList(studentBatchLogVo);
        return getDataTable(list);
    }


    @PostMapping("upload")
    public AjaxResult upload(MultipartFile file, HttpServletResponse response) throws Exception {
        return processUpload(file, response, 1); // 1表示导入信息
    }

    /**
     * 学籍信息导入
     */
    @PostMapping("uploadIn")
    public AjaxResult uploadIn(MultipartFile file, HttpServletResponse response) throws Exception {
        return processUpload(file, response, 2); // 2表示学籍信息导入
    }

    /**
     * 统一处理上传逻辑
     * @param file 上传文件
     * @param response HTTP响应
     * @param importType 导入类型 1-导入信息, 2-学籍信息导入
     * @return 处理结果
     */
    private AjaxResult processUpload(MultipartFile file, HttpServletResponse response, Integer importType) {
        try {
            ExcelUtil<BatchLogDetailVo> util = new ExcelUtil<>(BatchLogDetailVo.class);
            List<BatchLogDetailVo> uploadVos = util.importExcel(file.getInputStream());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            if (uploadVos.isEmpty()) {
                return error("请上传文件");
            }

            // 验证Excel模板是否正确（检查表头）
            if (!isValidTemplate(file)) {
                return error("模板不正确，请重新下载");
            }


            String batchId = simpleDateFormat.format(new Date());
            StudentBatchLogVo batchLogVo = new StudentBatchLogVo();
            batchLogVo.setBatchTime(new Date());
            batchLogVo.setBatchId(batchId);
            batchLogVo.setType("导入信息");
            batchLogVo.setCreateAt(SecurityUtils.getLoginUser().getUsername());
            batchLogVo.setNewsImport(importType);
            int errorCount = 0;
            for (BatchLogDetailVo info : uploadVos) {
                // 基础字段验证
                validateBasicFields(info);

                // 如果基础验证失败，跳过后续验证
                if (hasError(info)) {
                    errorCount++;
                    prepareRecordForSave(info, batchId, false);
                    continue;
                }
                // 关联数据验证
                boolean isValid = validateRelatedData(info);
                if (!isValid) {
                    errorCount++;
                }
                // 准备保存记录
                prepareRecordForSave(info, batchId, isValid);
            }

            // 设置批次状态
            batchLogVo.setStatus(errorCount > 0 ? 2L : 1L);

            // 保存数据
            String status = importType == 1 ?
                    batchLogDetailService.insertBatchLogDetails(uploadVos, batchLogVo) :
                    batchLogDetailService.insertBatchLogDetails1(uploadVos, batchLogVo);
            studentBatchLogService.insertStudentBatchLog(batchLogVo, status);
            return success("上传成功");
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return error("导入失败: " + e.getMessage());
        }
    }

    /**
     * 验证Excel模板是否正确（检查表头）
     * @param file 上传的文件
     * @return 模板是否正确
     */
    private boolean isValidTemplate(MultipartFile file) {
        try {
            ExcelUtil<BatchLogDetailVo> util = new ExcelUtil<>(BatchLogDetailVo.class);
            // 获取Excel的表头信息
            String[] headers = util.importExcelHeaders(file.getInputStream());

            if (headers == null || headers.length == 0) {
                return false;
            }

            // 定义必须包含的表头字段
            String[] requiredHeaders = {
                    "姓名", "性别", "身份证号", "学院名称",
                    "模式", "专业名称", "年级", "班级","学制(年)"
            };

            // 检查是否包含所有必需的表头
            for (String requiredHeader : requiredHeaders) {
                boolean found = false;
                for (String header : headers) {
                    if (requiredHeader.equals(header)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    return false;
                }
            }

            return true;
        } catch (Exception e) {
            logger.error("验证模板表头时出错", e);
            return false;
        }
    }

    /**
     * 基础字段验证
     */
    private void validateBasicFields(BatchLogDetailVo info) {
        if (isEmpty(info.getSchoolSystem())) {
            info.setErrorMessage("学制不能为空！");
        } else if (isEmpty(info.getEducation())) {
            info.setErrorMessage("模式不能为空！");
        } else if (isEmpty(info.getCollegeName())) {
            info.setErrorMessage("学院不能为空！");
        } else if (isEmpty(info.getMajorName())) {
            info.setErrorMessage("专业不能为空！");
        } else if (isEmpty(info.getGradeName())) {
            info.setErrorMessage("年级不能为空！");
        } else if (isEmpty(info.getName())) {
            info.setErrorMessage("姓名不能为空！");
        } else if (isEmpty(info.getIdNumber())) {
            info.setErrorMessage("身份证号不能为空！");
        } else if (info.getIdNumber() != null && info.getIdNumber().length() != 18) {
            info.setErrorMessage("身份证号不足18位或超出18位");
        } else {
            info.setStatus(1L); // 默认设置为成功状态
        }
    }

    /**
     * 关联数据验证
     */
    private boolean validateRelatedData(BatchLogDetailVo info) {
        try {
            // 验证学院信息
            SchoolCollegeVos schoolCollegeVos = new SchoolCollegeVos();
            schoolCollegeVos.setCollegeName(thoroughCleanString(info.getCollegeName().trim()));
            schoolCollegeVos.setDeleteFlag("0");
            R<List<SchoolCollegeVos>> collegeResult = remoteEduService.checkCollege(schoolCollegeVos);
            if (collegeResult.getData() == null || collegeResult.getData().isEmpty()) {
                info.setErrorMessage("学院不存在");
                return false;
            }

            SchoolCollegeVos college = collegeResult.getData().get(0);
            info.setCollegeId(college.getId());

            // 验证年级信息
            SchoolGradeVos schoolGradeVos = new SchoolGradeVos();
            schoolGradeVos.setGrade(thoroughCleanString(info.getGradeName().trim()));
            schoolGradeVos.setDeleteFlag("0");
            schoolGradeVos.setStatus("1");
            R<List<SchoolGradeVos>> gradeResult = remoteEduService.checkGrade(schoolGradeVos);

            if (gradeResult.getData() == null || gradeResult.getData().isEmpty()) {
                info.setErrorMessage("年级不存在");
                return false;
            }
            info.setGradeId(gradeResult.getData().get(0).getId());
            // 验证培养模式
            CollegeModelVos collegeModelVos = new CollegeModelVos();
            collegeModelVos.setModelName(thoroughCleanString(info.getEducation().trim()));
            collegeModelVos.setCollegeId(info.getCollegeId());
            collegeModelVos.setCampusId(college.getCampusId());
            collegeModelVos.setDeleteFlag("0");
            collegeModelVos.setStatus("1");
            R<List<CollegeModelVos>> modelResult = remoteEduService.checkEducation(collegeModelVos);
            if (modelResult.getData() == null || modelResult.getData().isEmpty()) {
                info.setErrorMessage("该分校，该学院中没有该模式");
                return false;
            }
            info.setEducationId(modelResult.getData().get(0).getId());

            // 验证专业信息
            CollegeMajorVos collegeMajorVos = new CollegeMajorVos();
            collegeMajorVos.setCollegeIds(String.valueOf(college.getId()));
            collegeMajorVos.setMajorName(thoroughCleanString(info.getMajorName().trim()));
            collegeMajorVos.setDeleteFlag("0");
            collegeMajorVos.setStatus("1");
            collegeMajorVos.setModelId(modelResult.getData().get(0).getId());
            R<List<CollegeMajorVos>> majorResult = remoteEduService.checkMajor(collegeMajorVos);

            if (majorResult.getData() == null || majorResult.getData().isEmpty()) {
                info.setErrorMessage("该分校，该学院中没有该专业");
                return false;
            }

            info.setMajorId(majorResult.getData().get(0).getId());

            // 获取校区信息
            SchoolCampusVos schoolCampusVos = new SchoolCampusVos();
            schoolCampusVos.setId(college.getCampusId());
            schoolCampusVos.setDeleteFlag("0");
            schoolCampusVos.setStatus("1");
            R<List<SchoolCampusVos>> campusResult = remoteEduService.checkCampus(schoolCampusVos);
            if (campusResult.getData() != null && !campusResult.getData().isEmpty()) {
                info.setBranchName(campusResult.getData().get(0).getCampusName());
                info.setCampusId(college.getCampusId());
            }

            StudentInfoVos studentInfoVos = new StudentInfoVos();
            studentInfoVos.setIdNumber(info.getIdNumber());
            studentInfoVos.setName(info.getName());
            R<List<StudentInfoVos>> listR = remoteUserService.queryVosByIdNumber(studentInfoVos);
            if (listR != null && listR.getData() != null && !listR.getData().isEmpty()) {
                info.setErrorMessage("该生已录入过");
                return false;
            }

            return true;
        } catch (Exception e) {
            logger.error("验证关联数据时出错", e);
            info.setErrorMessage("系统验证出错: " + e.getMessage());
            return false;
        }
    }
    /**
     * 准备记录保存数据
     */
    private void prepareRecordForSave(BatchLogDetailVo info, String batchId, boolean isValid) {
        info.setBatchId(batchId);
        info.setStatus(isValid ? 1L : 2L);
    }
    /**
     * 检查是否有错误信息
     */
    private boolean hasError(BatchLogDetailVo info) {
        return info.getErrorMessage() != null && !info.getErrorMessage().isEmpty();
    }
    /**
     * 检查字符串是否为空
     */
    private boolean isEmpty(String str) {
        return str == null || str.isEmpty();
    }

    /**
     * 重新上传学生信息（未在校状态）
     *
     * @param batchId 批次ID
     * @return 处理结果
     */
    @GetMapping("repeatUpload/{batchId}")
    public AjaxResult repeatUpload(@PathVariable String batchId) throws Exception{
        String message = studentBatchLogService.processBatchUpload(batchId,0L);
        if ("导入成功！".equals(message)) {
            return AjaxResult.success(message);
        }else{
            return AjaxResult.error(message);
        }

    }

    /**
     * 重新上传学生信息（在校状态）
     *
     * @param batchId 批次ID
     * @return 处理结果
     */
    @GetMapping("repeatUploadIn/{batchId}")
    public AjaxResult repeatUploadIn(@PathVariable String batchId) throws Exception{
        String message = studentBatchLogService.processBatchUpload(batchId,1L);
        if ("导入成功！".equals(message)) {
            return AjaxResult.success(message);
        }else{
            return AjaxResult.error(message);
        }
    }



    @PostMapping("/download")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            FileDownloadUtil.downloadExcelTemplate(
                    "static/工程大学学生导入模板.xlsx",
                    "工程大学学生导入模板.xlsx",
                    response
            );
        } catch (IOException e) {
            e.printStackTrace();
            try {
                response.getWriter().write("模板文件下载失败: " + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 更彻底地清理字符串
     * @param str 原始字符串
     * @return 清理后的字符串
     */
    private String thoroughCleanString(String str) {
        if (str == null) return null;
        // 去除首尾空格，然后去除所有特殊字符，只保留字母、数字、中文字符、空格和常见符号
        if (str == null) return null;
        // 去除首尾空白字符，将中间的换行符、制表符等替换为空格，然后将多个空格合并为单个空格
        return str.trim()
                .replaceAll("[\\r\\n\\t]", " ")
                .replaceAll("\\s+", " ");
    }




}
